/*
 * 作者: junmu
 * 时间: 2025-07-22
 */
package com.hzbc.faceattendance.controller;

import com.hzbc.faceattendance.dto.ApiResponse;
import com.hzbc.faceattendance.dto.WhiteListRequest;
import com.hzbc.faceattendance.model.WhiteList;
import com.hzbc.faceattendance.service.IWhitelistService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "白名单管理", description = "白名单相关接口")
@RestController
@RequestMapping("/api/whitelist")
public class WhitelistController {

    @Autowired
    private IWhitelistService whitelistService;

    @Operation(summary = "获取白名单列表", description = "根据关键词查询所有白名单记录")
    @PostMapping("/list")
    public ApiResponse<Page<WhiteList>> getAllWhitelist(@RequestBody WhiteListRequest request, @PageableDefault(size = 20, sort = "createTime", direction = Sort.Direction.DESC) Pageable pageable) {  // 明确指定排序方向) {

        try {
            Page<WhiteList> whiteLists = whitelistService.getAllWhitelist(request.getKeyword(), pageable);
            return new ApiResponse<>(true, 0, "获取白名单列表成功", whiteLists);
        } catch (IllegalArgumentException e) {  // 捕获参数异常
            return new ApiResponse<>(false, 400, "分页参数错误: " + e.getMessage(), null);
        } catch (UnsupportedOperationException e) {  // 捕获不支持操作异常
            return new ApiResponse<>(false, 400, "分页参数格式错误", null);
        }
    }

    @Operation(summary = "添加白名单")
    @PostMapping("/add")
    public ApiResponse<WhiteList> addToWhitelist(@RequestBody WhiteList whitelist) {
        WhiteList newWhiteList = whitelistService.addToWhitelist(whitelist);
        return new ApiResponse<>(true, 0, "添加白名单成功", newWhiteList);
    }

    @Operation(summary = "更新白名单")
    @PostMapping("/update")
    public ApiResponse<WhiteList> updateWhitelist( @RequestBody WhiteList whitelist) {
        WhiteList updatedWhiteList = whitelistService.updateWhitelist(whitelist.getId(), whitelist);
        return new ApiResponse<>(true, 0, "更新白名单成功", updatedWhiteList);
    }

    @Operation(summary = "删除白名单")
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteFromWhitelist(@PathVariable Long id) {
        whitelistService.deleteFromWhitelist(id);
        return new ApiResponse<>(true, 0, "删除白名单成功", null);
    }
}